package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.OrderPriceListAdapter;
import com.wuliupai.delivery.wuliupaidelivery.bean.OrderBean;
import com.wuliupai.delivery.wuliupaidelivery.bean.PayBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.Flag;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LocationUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.SelectUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.SharePreferenceUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * Class:确认下单
 * Created by KANG on 2016/11/22  13:37.
 * Email:khl8912@126.com
 */

@EActivity(R.layout.activity_order_place_sure)
public class OrderPlaceSureActivity extends AppBaseActivity {

    @ViewById(R.id.tv_fromPerson)
    TextView tv_fromPerson;//发货人
    @ViewById(R.id.tv_fromPhone)
    TextView tv_fromPhone;//发货电话
    @ViewById(R.id.tv_fromAddress)
    TextView tv_fromAddress;//发货地址

    @ViewById(R.id.tv_toPerson)
    TextView tv_toPerson;//收货人
    @ViewById(R.id.tv_toPhone)
    TextView tv_toPhone;//收货电话
    @ViewById(R.id.tv_toAddress)
    TextView tv_toAddress;//收货地址

    @ViewById(R.id.tv_goodsName)
    TextView tv_goodsName;//货物名称
    @ViewById(R.id.tv_goodsInfo)
    TextView tv_goodsInfo;//货物重量、体积、件数
    @ViewById(R.id.tv_goodsRemark)
    TextView tv_goodsRemark;//备注

    @ViewById(R.id.tv_userType)
    TextView tv_userType;//用户类型

    @ViewById(R.id.tv_salesman)
    TextView tv_salesman;//业务员

    @ViewById(R.id.tv_payWay)
    TextView tv_payWay;//支付方式

    @ViewById(R.id.btn_orderPlaceSure)
    Button btn_orderPlaceSure;//确认按钮

    @ViewById(R.id.lv_price)
    ListView lv_price;//费用列表

    @Extra("orderBean")
    OrderBean orderBean;
    @Extra("fromWhichPage")
    int fromWhichPage;//从哪个界面跳转，是否获取详情
    @Extra("priceInfoList")
    List<String[]> priceInfoList;
    @Extra("basePrice")
    String basePrice;
    @Extra("selfPickUpFreight")
    String selfPickUpFreight;
    @Extra("selfSendFreight")
    String selfSendFreight;
//    @Extra("salesmanName")
//    String salesmanName = ""; //业务员姓名

    private LocalBroadcastManager lbm;

    private String sProvince;
    private String sCity;
    private String sArea;
    private String sAddress;
    private String rProvince;
    private String rCity;
    private String rArea;
    private String rAddress;
    private String consignorName;
    private String consignorMobile;
    private String consigneeName;
    private String consigneeMobile;
    private String goodsName;
    private String goodsWeight;
    private String goodsVolume;
    private String remarks;
    private String salesman;
    private String payType;
    private String orderCode;
    private String dealPrice;
    private String status;
    private String gps_x;
    private String gps_y;
    private String goodsCount;
    private String calculateType;

    private int lastMoney;//最终需要支付的金额

    @AfterViews
    void startOrderPlaceSure() {
        lbm = LocalBroadcastManager.getInstance(this);
        LocationUtil.getAndSaveLocation2SharePreference(OrderPlaceSureActivity.this);
        gps_x = SharePreferenceUtil.getLocation(OrderPlaceSureActivity.this).getGps_x();
        gps_y = SharePreferenceUtil.getLocation(OrderPlaceSureActivity.this).getGps_y();
        if (Flag.ToPlaceOrder_FromOrderDetail == fromWhichPage) {//确认修改
            setDefaultTitle(this, R.string.string_alter_order);
            btn_orderPlaceSure.setText(getString(R.string.string_place_order_sure_alter));
            showOrderPlaceInfo();
        } else {//确认下单
            setDefaultTitle(this, R.string.string_placeOrderV2_title);
            btn_orderPlaceSure.setText(getString(R.string.string_place_order_sure));
            showOrderPlaceInfo();
        }
    }

    /**
     * 显示下单数据
     */
    private void showOrderPlaceInfo() {
        sProvince = orderBean.getStartProvince();
        sCity = orderBean.getStartCity();
        sArea = orderBean.getStartArea();
        sAddress = orderBean.getStartAddress();
        rProvince = orderBean.getEndProvince();
        rCity = orderBean.getEndCity();
        rArea = orderBean.getEndArea();
        rAddress = orderBean.getEndAddress();
        consignorName = orderBean.getConsignorName();
        consignorMobile = orderBean.getConsignorMobile();
        consigneeName = orderBean.getConsigneeName();
        consigneeMobile = orderBean.getConsigneeMobile();
        goodsName = orderBean.getGoodsName();
        goodsWeight = orderBean.getGoodsWeight();
        goodsCount = orderBean.getGoodsCount();
        calculateType = orderBean.getCalculateType();
        goodsVolume = orderBean.getGoodsVolume();
        remarks = orderBean.getRemarks();
        salesman = orderBean.getSalesman();
        payType = orderBean.getPayType();
        orderCode = orderBean.getOrderCode();
        dealPrice = orderBean.getDealPrice();
        status = orderBean.getStatus();
        tv_fromAddress.setText(orderBean.getsProvinceCityArea() + sAddress);
        tv_fromPerson.setText(consignorName);
        tv_fromPhone.setText(consignorMobile);
        tv_toAddress.setText(orderBean.getrProvinceCityArea() + rAddress);
        tv_toPerson.setText(consigneeName);
        tv_toPhone.setText(consigneeMobile);
        tv_goodsName.setText(goodsName);

        String weight = StringUtils.formatWeight(goodsWeight);//重量;
        String volume = StringUtils.formatVolume(goodsVolume);//体积;
        tv_goodsInfo.setText(weight + " " + volume + " " + goodsCount + "件");
        tv_userType.setText(SelectUtil.initUserType().get(calculateType));
        if (StringUtils.isEmpty(remarks)) {
            tv_goodsRemark.setHint("无备注");
        } else {
            tv_goodsRemark.setText(remarks);
        }
        tv_payWay.setText(SelectUtil.initPayWay().get(orderBean.getPayType()));
        if (StringUtils.isEmpty(salesman)) {
            tv_salesman.setText(R.string.strings_common_noFill);
        } else {
            tv_salesman.setText(salesman);
        }

        List<String[]> priceList = new ArrayList<>();
        priceList.addAll(priceInfoList);
        priceList.add(0, new String[]{"运输费用", StringUtils.format2Yuan(basePrice) + "元"});

        lastMoney = Integer.valueOf(dealPrice);
        if (Flag.ToPlaceOrder_FromOrderDetail == fromWhichPage) {//修改订单
            String tempActualMoney = orderBean.getActualMoney();
            priceList.add(new String[]{"已付费用", "-" + StringUtils.format2Yuan(tempActualMoney) + "元"});
            lastMoney = Integer.valueOf(dealPrice) - Integer.valueOf(tempActualMoney);
        }
        if (lastMoney < 0) {
            priceList.add(new String[]{"应付金额", "0元"});
        } else {
            priceList.add(new String[]{"应付金额", StringUtils.format2Yuan(lastMoney + "") + "元"});
        }

        OrderPriceListAdapter adapter = new OrderPriceListAdapter(this, priceList);
        lv_price.setAdapter(adapter);
    }

    @Click(R.id.btn_orderPlaceSure)
    void orderPlaceSure() {
        if (StringUtils.isEmpty(dealPrice)) {
            dealPrice = "0";
        }

        if (Flag.ToPlaceOrder_FromOrderDetail == fromWhichPage) {//确认修改
            //  修改订单
            submitOrderPlace(InterfaceNet.Net_EditOrder);
        } else {//确认下单
            submitOrderPlace(InterfaceNet.Net_CreateOrder);
        }
    }

    /**
     * 确认下单
     */
    private void submitOrderPlace(String url) {
        if (StringUtils.isEmpty(gps_x)) {
            gps_x = "0.0";
        }
        if (StringUtils.isEmpty(gps_y)) {
            gps_y = "0.0";
        }
        OrderBean orderPlace = new OrderBean(consignorName, consignorMobile, consigneeName, consigneeMobile, sProvince, sCity, sArea, sAddress,
                rProvince, rCity, rArea, rAddress, goodsName, goodsWeight, goodsVolume, dealPrice, remarks, payType, status, gps_x, gps_y, goodsCount, calculateType);
        orderPlace.setSelfPickUpFreight(selfPickUpFreight);
        orderPlace.setSelfSendFreight(selfSendFreight);
        orderPlace.setSalesman(salesman);

        String startGpsX = orderBean.getStartGpsX();
        String startGpsY = orderBean.getStartGpsY();
        String endGpsX = orderBean.getEndGpsX();
        String endGpsY = orderBean.getEndGpsY();
        orderPlace.setStartGpsX(StringUtils.isEmpty(startGpsX) ? "0" : startGpsX);
        orderPlace.setStartGpsY(StringUtils.isEmpty(startGpsY) ? "0" : startGpsY);
        orderPlace.setEndGpsX(StringUtils.isEmpty(endGpsX) ? "0" : endGpsX);
        orderPlace.setEndGpsY(StringUtils.isEmpty(endGpsY) ? "0" : endGpsY);
        if (Flag.ToPlaceOrder_FromOrderDetail == fromWhichPage) {//确认修改
            orderPlace.setOrderCode(orderCode);
        }
        String jsonOrderPlace = JsonUtils.createJsonString(orderPlace);
        LogUtils.log("确认下单send---" + jsonOrderPlace);
        try {
            String aesOrderPlace = JsonUtils.aes(jsonOrderPlace);
            callNet(OrderPlaceSureActivity.this, url, aesOrderPlace, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {

                    Intent intent = new Intent(BroadcastChannels.Channel_CreateOrderSuccessFully);
                    lbm.sendBroadcast(intent);

                    if ("1".equals(payType)//在线支付
                            || "5".equals(payType)//预付
                            ) {
                        if (!StringUtils.isEmpty(content)) {
                            OrderBean parseOrderPlace = (OrderBean) JsonUtils.parseJsonString(content, OrderBean.class);
                            orderCode = parseOrderPlace.getOrderCode();
                        } else {
                            orderCode = orderBean.getOrderCode();
                        }
                        showPay(orderCode);
                    } else {
                        finishCurrentPageAfterPlaceOrderSuccess();
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下单成功后关闭页面
     */
    private void finishCurrentPageAfterPlaceOrderSuccess() {
        if (Flag.ToPlaceOrder_FromOrderDetail == fromWhichPage) {
            App.toast("订单修改成功");
            finish();
            animUtils.leftOutAnimation(OrderPlaceSureActivity.this);
        } else if (Flag.ToPlaceOrder_FromCurrentMission == fromWhichPage) {
            App.toast("下单成功");
            finish();
            animUtils.leftOutAnimation(OrderPlaceSureActivity.this);
        } else {
            App.toast("下单成功");
            finish();
            animUtils.leftOutAnimation(OrderPlaceSureActivity.this);
        }
    }

    /**
     * 选择支付时间
     */
    private void showPay(String orderCode) {
        new AlertDialog.Builder(OrderPlaceSureActivity.this)
                .setTitle(getString(R.string.string_pay_title))
                .setMessage(getString(R.string.string_pay_content))
                .setNegativeButton(getString(R.string.string_pay_later), (dialogInterface, i) -> {
                    //稍后支付
                    finishCurrentPageAfterPlaceOrderSuccess();
                }).setPositiveButton(getString(R.string.string_pay_now), (dialogInterface, i) -> {
            //现在支付
            //payFeel:[0]支付类型，[1]支付金额
            PayFeeActivity_.intent(OrderPlaceSureActivity.this)
                    .payBean(new PayBean(PayFeeActivity.PayType_Freight, Long.valueOf(lastMoney)))
                    .orderCode(orderCode).start();
            finish();
            animUtils.popOutAnimation(OrderPlaceSureActivity.this);
        }).show();
    }
}